package com.nehc.nettyserver.controller;

import com.nehc.nettyserver.common.model.ClientInfo;
import com.nehc.nettyserver.netty.ChannelManager;
import com.nehc.nettyserver.service.MessageService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 服务器状态控制器
 * 提供服务器状态相关API
 * 
 * @author NEHC
 */
@RestController
@RequestMapping("/server")
@RequiredArgsConstructor
public class ServerStatusController {
    
    private final ChannelManager channelManager;
    private final MessageService messageService;
    
    /**
     * 获取服务器状态
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getServerStatus() {
        Map<String, Object> status = new HashMap<>();
        
        // 基本信息
        status.put("startTime", System.currentTimeMillis());
        status.put("version", "1.0.0");
        
        // 连接统计
        status.put("connectionCount", channelManager.getConnectionCount());
        status.put("onlineUserCount", channelManager.getOnlineUserCount());
        
        // 消息统计
        status.put("messageStats", messageService.getMessageStats(
                System.currentTimeMillis() - 24 * 60 * 60 * 1000, // 24小时前
                System.currentTimeMillis()
        ));
        
        return ResponseEntity.ok(status);
    }
    
    /**
     * 获取所有客户端信息
     */
    @GetMapping("/clients")
    public ResponseEntity<Map<String, ClientInfo>> getAllClients() {
        return ResponseEntity.ok(channelManager.getAllClientInfo());
    }
    
    /**
     * 获取指定客户端信息
     */
    @GetMapping("/clients/{clientId}")
    public ResponseEntity<ClientInfo> getClientInfo(@PathVariable String clientId) {
        ClientInfo clientInfo = channelManager.getClientInfo(clientId);
        if (clientInfo != null) {
            return ResponseEntity.ok(clientInfo);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 断开指定客户端连接
     */
    @DeleteMapping("/clients/{clientId}")
    public ResponseEntity<Map<String, Object>> disconnectClient(
            @PathVariable String clientId,
            @RequestParam(defaultValue = "管理员断开连接") String reason) {
        
        Map<String, Object> result = new HashMap<>();
        ClientInfo clientInfo = channelManager.getClientInfo(clientId);
        
        if (clientInfo != null && clientInfo.isConnected()) {
            // TODO: 实现断开连接逻辑
            result.put("success", true);
            result.put("message", "客户端已断开连接");
            return ResponseEntity.ok(result);
        } else {
            result.put("success", false);
            result.put("message", "客户端不存在或已断开连接");
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 向指定客户端发送消息
     */
    @PostMapping("/clients/{clientId}/message")
    public ResponseEntity<Map<String, Object>> sendMessageToClient(
            @PathVariable String clientId,
            @RequestBody Map<String, Object> messagePayload) {
        
        Map<String, Object> result = new HashMap<>();
        
        if (messagePayload == null || !messagePayload.containsKey("content")) {
            result.put("success", false);
            result.put("message", "消息内容不能为空");
            return ResponseEntity.badRequest().body(result);
        }
        
        String content = messagePayload.get("content").toString();
        boolean success = channelManager.sendToClient(clientId, content);
        
        result.put("success", success);
        result.put("message", success ? "消息发送成功" : "消息发送失败");
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 向所有客户端广播消息
     */
    @PostMapping("/broadcast")
    public ResponseEntity<Map<String, Object>> broadcastMessage(
            @RequestBody Map<String, Object> messagePayload) {
        
        Map<String, Object> result = new HashMap<>();
        
        if (messagePayload == null || !messagePayload.containsKey("content")) {
            result.put("success", false);
            result.put("message", "消息内容不能为空");
            return ResponseEntity.badRequest().body(result);
        }
        
        String content = messagePayload.get("content").toString();
        int count = channelManager.broadcast(content);
        
        result.put("success", true);
        result.put("message", "广播消息已发送");
        result.put("recipientCount", count);
        
        return ResponseEntity.ok(result);
    }
} 